<?php

namespace app\api\controller;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Controller;

class Upload extends Controller
{
    /**
     * 上传图片到七牛云
     */
    public function save_upload()
    {
        $file = request()->file('file');
        // 要上传图片的本地路径
        $filePath = $file->getRealPath();
        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
        // 上传到七牛后保存的文件名
        $key = substr(md5($file->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $ext;
        // 需要填写你的 Access Key 和 Secret Key
        // 构建鉴权对象
        $accessKey = 'nzBkKSUtadKyyCLsgST0uyTlErzRjoWJA44dT4AV';
        $secretKey = 'mg-90H4Nz9Q8IMRpyc7-m0cILUl2XS-7f1EMb1sj';
        $auth = new Auth($accessKey, $secretKey);
        // 要上传的空间
        $bucket = '1810phpa';
        //域名
        $domain = 'quu0m8pq4.hb-bkt.clouddn.com';
        $token = $auth->uploadToken($bucket);
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list( $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return ["code" => 1];
        } else {
            //返回图片的完整URL
            $imgPath = 'http://' . $domain . '/' . $key;
            //赋值
            return json(['code' => 0, 'url' => $imgPath, 'type' => 1, 'name' => $key]);
        }
    }
}